package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.sqlsession.MapperMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        SqlCommandType[] nodeType = {SqlCommandType.SELECT,SqlCommandType.INSERT,SqlCommandType.UPDATE,SqlCommandType.DELETE};

        for (SqlCommandType sqlCommandType : nodeType) {
            List<Element> selectlist = rootElement.selectNodes(sqlCommandType.name().toLowerCase());
            for (Element element : selectlist) {
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setMethodType(sqlCommandType);
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String paramterType = element.attributeValue("paramterType");
                String sql = element.getTextTrim();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setSql(sql);
                String key = namespace+"."+id;

                configuration.getMappedStatementMap().put(key,mappedStatement);
            }
        }


    }
}
